//
//  LanguageManager.swift
//  SCA
//
//  Created by tjun on 2025/9/2.
//

import UIKit

extension String {
    var localizedString: String {
        return LanguageManager.shared.localizedString(for: self)
    }
    
    func localizedString(tableName: String?) -> String {
        return LanguageManager.shared.localizedString(for: self, tableName: tableName)
    }
}

enum AppLanguage: String {
    case chineseSimplified = "zh-Hans"
    case chineseTraditional = "zh-HK"
    case english = "en"
    case korea = "ko"
    case japanese = "ja"

    
    var description: String {
        switch self {
        case .english: return "English"
        case .chineseSimplified: return "中文"
        case .chineseTraditional: return "繁體中文"
        case .korea: return "한국어"
        case .japanese: return "にほんご"
        }
    }
    
    var serviceLanguage: String {
        switch self {
        case .chineseSimplified: return "cn"
        case .chineseTraditional: return "cnt"
        case .english: return "en"
        case .korea: return "kr"
        case .japanese: return "jp"
        }
    }
}

class LanguageManager {
    
    static let shared = LanguageManager()
        
    var currentLanguage: AppLanguage {
        didSet {
            guard oldValue != currentLanguage else { return }
            UserDefaults.standard.set(currentLanguage.rawValue, forKey: "AppLanguage")
            UserDefaults.standard.synchronize()
            updateBundleLanguage()
            NotificationCenter.default.post(name: NotificationName.languageDidChange, object: currentLanguage)
        }
    }
    
    private var originalBundle = Bundle.main
    private var languageBundle: Bundle?
    
    private init() {
        if let saved = UserDefaults.standard.string(forKey: "AppLanguage"),
           let lang = AppLanguage(rawValue: saved) {
            currentLanguage = lang
        } else {
            let preferred = Locale.preferredLanguages.first ?? "en"
            if preferred.hasPrefix("zh") {
                currentLanguage = .chineseSimplified
            } else {
                currentLanguage = .english
            }
        }
    }
    
    func setLanguage() {
        updateBundleLanguage()
    }
    
    func localizedString(for key: String, tableName: String? = nil) -> String {
        return languageBundle?.localizedString(forKey: key, value: nil, table: tableName) ?? key
    }
    
    private func updateBundleLanguage() {
        if let path = originalBundle.path(forResource: currentLanguage.rawValue, ofType: "lproj"),
           let bundle = Bundle(path: path) {
            languageBundle = bundle
        } else {
            languageBundle = originalBundle
        }
    }
}
